/// Author: Shper
/// Created: 2023/9/22
class GTLoggerColor {

  static const ansiEsc = '\x1B[';

  static const ansiDefault = '${ansiEsc}0m';

  final int? fg;
  final int? bg;
  final bool color;

  const GTLoggerColor.none()
      : fg = null,
        bg = null,
        color = false;

  const GTLoggerColor.green()
      : fg = 40,
        bg = null,
        color = true;

  const GTLoggerColor.blue()
      : fg = 12,
        bg = null,
        color = true;

  const GTLoggerColor.yellow()
      : fg = 11,
        bg = null,
        color = true;

  const GTLoggerColor.red()
      : fg = 9,
        bg = null,
        color = true;

  const GTLoggerColor.fg(this.fg)
      : bg = null,
        color = true;

  const GTLoggerColor.bg(this.bg)
      : fg = null,
        color = true;

  @override
  String toString() {
    if (fg != null) {
      return '${ansiEsc}38;5;${fg}m';
    } else if (bg != null) {
      return '${ansiEsc}48;5;${bg}m';
    } else {
      return '';
    }
  }

  String call(String msg) {
    if (color) {
      // ignore: unnecessary_brace_in_string_interps
      return '${this}$msg$ansiDefault';
    } else {
      return msg;
    }
  }

  GTLoggerColor toFg() => GTLoggerColor.fg(bg);

  GTLoggerColor toBg() => GTLoggerColor.bg(fg);

  String get resetForeground => color ? '${ansiEsc}39m' : '';

  String get resetBackground => color ? '${ansiEsc}49m' : '';

  static int grey(double level) => 232 + (level.clamp(0.0, 1.0) * 23).round();
}
